﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Text;

namespace MII_FIF.Layouts.MII_FIF.FormApproval
{
    public partial class Approval_DataKunjungan : LayoutsPageBase
    {
        SqlConnection conn;
        DataTable dt;
        SqlDataAdapter adapt;
        //string connStr = "Data Source=sp2013-server;Initial Catalog=InventoryManagement;User ID=sa;Password=P@ssw0rd";
        string queryStr = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            btnCancel.Click += btnCancel_Click;
            btnCancel2.Click += btnCancel2_Click;
            btnApprove.Click += btnApprove_Click;
            btnReject.Click += btnReject_Click;
            //btnRemove.Click += btnRemove_Click;

            if (!IsPostBack)
            {
                    grpKunjungan.Visible = false;
                    grpTrouble.Visible = false;
                    grpDeployment.Visible = false;
                    grpLain.Visible = false;
                    ViewState["ID"] = Request.QueryString["ID"].ToString();
                    LoadDataView(ViewState["ID"].ToString());
            }
        }

        //void btnRemove_Click(object sender, EventArgs e)
        //{
        //    queryStr = @"SP_DeleteDataKunjungan '" + Request.QueryString["ID"].ToString() + "'";
        //    ExecuteDataTable(queryStr);
        //}

        protected DataTable ExecuteDataTable(string queryStr)
        {
            //conn = new SqlConnection(connStr);
            conn = new SqlConnection(Configuration.DBConnection());
            conn.Open();
            adapt = new SqlDataAdapter(queryStr, conn);
            dt = new DataTable();
            adapt.Fill(dt);
            conn.Dispose();
            return dt;
        }

        void LoadDataView(String ID)
        {
            try
            {
                queryStr = @"EXEC SP_SelectDataViewKunjunganperID '" + ID + "'";

                dt = ExecuteDataTable(queryStr);
                int i = 0;

                lblLogin.Text = dt.Rows[i]["PICHO"].ToString();
                String[] tanggal = dt.Rows[i]["Tanggal"].ToString().Split(' ');
                txtDate.Text = tanggal[0].ToString();
                lblTelepon.Text = dt.Rows[i]["Telp"].ToString();
                lblPICCabang.Text = dt.Rows[i]["PIC"].ToString();
                lblTlpPIC.Text = dt.Rows[i]["HP"].ToString();

                ddlLokasi.Enabled = false;
                ddlLokasi.Items.Add(new ListItem(dt.Rows[i]["Cabang"].ToString(), dt.Rows[i]["DataCabang"].ToString()));

                String KunjunganRutin = dt.Rows[i]["KunjunganRutin"].ToString();
                String TroubleCabang = dt.Rows[i]["TroubleCabang"].ToString();
                String DeploymentUnit = dt.Rows[i]["DeploymentUnit"].ToString();
                String Lain2 = dt.Rows[i]["LainLain"].ToString();
                String Status = dt.Rows[i]["wfStatus"].ToString();
				String Requester = dt.Rows[i]["Requester"].ToString();
                ViewState["Requester"] = Requester;
                txtComment.Text = dt.Rows[i]["Comment"].ToString();
                lblAction.Text = dt.Rows[i]["AppAction"].ToString();

                if (KunjunganRutin == "True")
                {
                    checkKunjungan.SelectedValue = "1";
                    grpKunjungan.Visible = true;
                    txtDesKunjungan.Text = dt.Rows[i]["DeskripsiKunjungan"].ToString();
                }
                if (Lain2 == "True")
                {
                    checkLain.SelectedValue = "4";
                    grpLain.Visible = true;
                    txtDesLain.Text = dt.Rows[i]["DeskripsiLain2"].ToString();
                }
                if (TroubleCabang == "True")
                {
                    checkTrouble.SelectedValue = "2";
                    grpTrouble.Visible = true;
                    LoadTrouble(ID);
                }
                if (DeploymentUnit == "True")
                {
                    checkDeployment.SelectedValue = "3";
                    grpDeployment.Visible = true;
                    LoadDeployment(ID);
                }

                if (Status != "Waiting for approval")
                {
                    btnApprove.Visible = false;
                    btnReject.Visible = false;
                    btnCancel.Visible = false;
                    txtComment.Enabled = false;
                    btnCancel2.Visible = true;
                    //btnRemove.Visible = true;
                    barislblAction.Visible = true;
                }
                else
                {
                    btnApprove.Visible = true;
                    btnReject.Visible = true;
                    btnCancel.Visible = true;
                    btnCancel2.Visible = false;
                    //btnRemove.Visible = false;
                    barislblAction.Visible = false;
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }

        void LoadTrouble(String ID)
        {
            try
            {

                queryStr = @"SP_SelectDataTroubleperlabelID '" + ID + "'";

                dt = ExecuteDataTable(queryStr);

                GridTrouble.DataSource = dt;
                GridTrouble.DataBind();
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }

        void LoadDeployment(String ID)
        {
            try
            {
                //Printer
                queryStr = @"SP_SelectDataPrinterKunjunganlabelID '" + ID + "'";
                dt = ExecuteDataTable(queryStr);
                ViewState["DTPrinter"] = dt;
                GridPrinter.DataSource = ViewState["DTPrinter"];
                GridPrinter.DataBind();

                //Unit
                queryStr = @"EXEC SP_SelectDataDeploymentUnitLabel '" + ID + "'";
                dt = ExecuteDataTable(queryStr);
                int i = 0;
                txtDesktop.Text = dt.Rows[i]["JmlDesktop"].ToString();
                txtNotebook.Text = dt.Rows[i]["JmlNotebook"].ToString();
                txtThinClient.Text = dt.Rows[i]["JmlThinClient"].ToString();
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }

        void btnCancel_Click(object sender, EventArgs e)
        {
            //Untuk Task
            Response.Redirect(Generic.GenLink("/_Layouts/MII_FIF/FormApproval/Task.aspx"));
        }

        void btnCancel2_Click(object sender, EventArgs e)
        {
            //Untuk View
            Response.Redirect(Generic.GenLink("/_Layouts/MII_FIF/DataKunjungan/ViewDataKunjungan.aspx"));
        }

        void btnApprove_Click(object sender, EventArgs e)
        {
            String TroubleCabang = checkTrouble.SelectedValue.ToString();
            String DeploymentUnit = checkDeployment.SelectedValue.ToString();

            String Desktop = txtDesktop.Text.ToString();
            String Notebook = txtNotebook.Text.ToString();
            String Thinclient = txtThinClient.Text.ToString();

            String Approver = SPContext.Current.Web.CurrentUser.Name;

            try
            {
                queryStr = @"EXEC SP_SelectDataViewKunjunganperID '" + Request.QueryString["ID"].ToString() + "'";
                dt = ExecuteDataTable(queryStr);
                int i = 0;

                String IDCabang = dt.Rows[i]["DataCabang"].ToString();

                //update wfStatus 'Approved' data cabang
                queryStr = @"EXEC SP_UpdateStatusDataKunjungan 'Approved','" + Request.QueryString["ID"].ToString() + "'";
                dt = ExecuteDataTable(queryStr);

                if (DeploymentUnit != "")
                {
                    //update column Jml to table cabang
                    queryStr = @"EXEC SP_UpdateDeploymentUnitDataCabang '" + Desktop + "','" + Notebook + "','" + Thinclient + "','" + IDCabang + "'";
                    dt = ExecuteDataTable(queryStr);

                    //delete from table Detail Printer
                    queryStr = @"EXEC SP_DeleteDataDetailPrinter '" + IDCabang + "'";
                    dt = ExecuteDataTable(queryStr);

                    //insert to table Detail Printer
                    using (DataTable dtPrinter = ViewState["DTPrinter"] as DataTable)
                    {
                        foreach (DataRow row in dtPrinter.Rows)
                        {
                            queryStr = @"SP_InsertDataDetailPrinter '" + IDCabang + "', '" + row["ID"].ToString() + "','" + row["JmlPrinter"].ToString() + "'";
                            ExecuteDataTable(queryStr);
                        }

                    }
                }

                #region Approval

                queryStr = @"EXEC SP_UpdateDataApproval '" + Request.QueryString["ID"].ToString() + "','" + Generic.GetUserLoginReformat() + "','Approve','" + txtComment.Text + "'";
                dt = ExecuteDataTable(queryStr);

                #endregion

                RedirectPageView("Approved");
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }

        void btnReject_Click(object sender, EventArgs e)
        {
            try
            {
                String Approver = SPContext.Current.Web.CurrentUser.Name;

                //update wfStatus 'Rejected' data cabang
                queryStr = @"EXEC SP_UpdateStatusDataKunjungan 'Rejected','" + Request.QueryString["ID"].ToString() + "'";
                dt = ExecuteDataTable(queryStr);

                #region Approval

                queryStr = @"EXEC SP_UpdateDataApproval '" + Request.QueryString["ID"].ToString() + "','" + Generic.GetUserLoginReformat() + "','Reject','" + txtComment.Text + "'";
                dt = ExecuteDataTable(queryStr);

                #endregion
				
				#region Email
                        StringBuilder sb = new StringBuilder();
                        sb.Append("Request Data Kunjungan Rejected By " + SPContext.Current.Web.CurrentUser.Name);
                        Generic.sendEmailSMTP("System@fif.co.id", Generic.getEmailUser(ViewState["Requester"].ToString()), "Request Rejected", sb.ToString());
                #endregion

                RedirectPageView("Rejected");
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
        }

        void RedirectPageView(String status)
        {
            Response.Redirect(Generic.GenLink("/_Layouts/MII_FIF/DataKunjungan/ViewDataKunjungan.aspx?Status=" + status + ""));
        }
    }
}
